package com.ebeitech.doorapp.view.homepage;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.constants.CommonConstants;
import com.ebeitech.doorapp.domain.EMessage;
import com.ebeitech.doorapp.domain.dao.EMessageDao;
import com.ebeitech.doorapp.qqim.util.QQIMUtil;
import com.ebeitech.doorapp.view.ChatActivity;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.setting.SettingActivity;
import com.ebeitech.library.constant.MessageConstants;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.badgeview.Badge;
import com.ebeitech.library.ui.badgeview.QBadgeView;
import com.ebeitech.library.util.Log;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.ViewUtil;
import com.ebeitech.library.util.view.StatusBarCompat;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by alice on 2017/10/30.
 */
public class HomepageActivity extends ActivityGroup {

	public static final int TAB_HOME = 0;
	public static final int TAB_APP_LIST = 1;
	public static final int TAB_USER = 2;

	@BindView(R.id.tvTitle)
	TextView mTvTitle;
	@BindView(R.id.ivTitleProgress)
	View mTitleProgressBar;
	@BindView(R.id.btnBack)
	View btnBack;
	@BindView(R.id.view_bottom)
	LinearLayout mBottomView;

	private Context mContext;
	private int mCurrentIndex;
	private int mLastIndex;

	private boolean isFitStatusBar = true;
	private boolean isHomeShowVersionDialog = false;

	private boolean isLoadingMessage = false;
	private boolean isNeedLoadMessage = false;
	private AsyncTask<Void, Void, Void> mMessageTask;
	private EMessageDao mMessageDao;

	@OnClick({R.id.btnBack})
	void onBtnBackClick(View view) {
		onBackPressed();
	}

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent != null) {
				String action = intent.getAction();
				if (MessageConstants.ACTION_CONNECT_STATUS.equals(action)) {
					int connectStatus = intent.getIntExtra(MessageConstants.CONNECT_STATUS, MessageConstants.DISCONNECTED);
					mConnectHandler.sendEmptyMessage(connectStatus);
				} else if (MessageConstants.ACTION_MESSAGE_RECEIVE.equals(action)
						|| MessageConstants.ACTION_MESSAGE_COUNT_CHANGE.equals(action)) {
					if (!isLoadingMessage) {
						loadMessageCount();
					} else {
						isNeedLoadMessage = true;
					}
				}
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ebei_activity_homepage);
		ButterKnife.bind(this);
		initView();
		mMessageDao = EMessageDao.getInstance();
		if (CommonConstants.IS_MESSAGE_OPEN) {
			QQIMUtil.getInstance().doLogin(this, SPManager.getInstance(mContext).get(SPConstants.USER_ACCOUNT, ""));
		}
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(MessageConstants.ACTION_CONNECT_STATUS);
		intentFilter.addAction(MessageConstants.ACTION_MESSAGE_RECEIVE);
		intentFilter.addAction(MessageConstants.ACTION_MESSAGE_COUNT_CHANGE);
		registerReceiver(mReceiver, intentFilter);

		isFitStatusBar = StatusBarCompat.setStatusBar(this, null);
		if (isFitStatusBar) {
			StatusBarCompat.compat(this);
		}

		loadMessageCount();
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (isFitStatusBar) {
			StatusBarCompat.fitsSystemWindows(this);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);

		if(mMessageTask != null){
			mMessageTask.cancel(true);
			mMessageTask = null;
		}
	}

	private void initView() {
		isHomeShowVersionDialog = getIntent().getBooleanExtra("isHomeShowVersionDialog",false);
		if (isHomeShowVersionDialog)
			PublicUtil.checkVersion(this);
		mContext = this;
		btnBack.setVisibility(View.INVISIBLE);

		findViewById(R.id.titleBar).setVisibility(View.GONE);
		initBottomView();
	}

	private Integer[] tabIds = new Integer[] {
			R.drawable.ebei_tab_btn_message_normal,
			R.drawable.ebei_tab_btn_work_normal,
			R.drawable.ebei_tab_btn_user_normal
	};
	private Integer[] tabIdSelects = new Integer[] {
			R.drawable.ebei_tab_btn_message_pressed,
			R.drawable.ebei_tab_btn_work_pressed,
			R.drawable.ebei_tab_btn_user_pressed
	};
	private void initBottomView() {
		String[] tabs = new String[] {
				getString(R.string.ebei_message),
				"应用",
				"我的"
		};

		int width = ViewUtil.getScreenSize(this).widthPixels / tabIds.length;
		for (int i = 0; i < tabs.length; i++) {
			View view = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_homepage_bottom, null);
			int margin = ViewUtil.dp2px(mContext, 2);
			view.setPadding(0, margin, 0, margin);
			final TextView tabText = (TextView) view.findViewById(R.id.tvName);
			final ImageView ivImage = (ImageView) view.findViewById(R.id.ivImage);
			if (imageWidth == 0) {
				imageWidth = ViewUtil.dp2px(mContext, 27);
			}
			ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) ivImage.getLayoutParams();
			lp.width = (int) imageWidth;
			lp.height = (int) imageWidth;
			ivImage.setLayoutParams(lp);
			final int position = i;
			tabText.setText(tabs[i]);
			tabText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
			tabText.setPadding(0, ViewUtil.dp2px(mContext, 2), 0, 0);
			ivImage.setImageResource(tabIds[i]);
			ivImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
			ivImage.setPadding(0, ViewUtil.dp2px(mContext, 3), 0, 0);
			view.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					mCurrentIndex = position;
					if (mCurrentIndex != mLastIndex) {
						updateBottomView();
						onTabSelected(mCurrentIndex);
						mLastIndex = mCurrentIndex;
					}
				}
			});
			mBottomView.addView(view, new LinearLayout.LayoutParams(width, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
		}
		mLastIndex = -1;
		mBottomView.getChildAt(mCurrentIndex).performClick();
	}

	private void updateBottomView() {
		if (mLastIndex > -1) {
			View view = mBottomView.getChildAt(mLastIndex);
			view.setSelected(false);//用了QBadgeView后，ivImage有时候setSelected变不过来
			ImageView ivImage = view.findViewById(R.id.ivImage);
			ivImage.setImageResource(tabIds[mLastIndex]);
		}

		View selectView = mBottomView.getChildAt(mCurrentIndex);
		selectView.setSelected(true);
		ImageView ivImage = selectView.findViewById(R.id.ivImage);
		ivImage.setImageResource(tabIdSelects[mCurrentIndex]);
	}

	private float imageWidth;
	@SuppressLint("StaticFieldLeak")
	private void loadMessageCount() {
		isLoadingMessage = true;
		mMessageTask = new AsyncTask<Void, Void, Void>() {
			int count = 0;
			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				if(mMessageTask.isCancelled()){
					return null;
				}
				count = mMessageDao.queryCount("readFlag = '" + EMessage.READ_FLAG_UNREAD + "'", null);
				return null;
			}
			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				if(mMessageTask.isCancelled()){
					return;
				}

				if (isNeedLoadMessage) {
					isNeedLoadMessage = false;
					loadMessageCount();
				}

				ViewGroup view = (ViewGroup) mBottomView.getChildAt(0);
				View ivImage = view.findViewById(R.id.ivImage);
				Object[] objs = (Object[]) view.getTag();
				if (objs == null) {
					objs = new Object[2];
					view.setTag(objs);
				}
				QBadgeView mQBadgeView = (QBadgeView) objs[0];
				Badge badge = (Badge) objs[1];
				if (mQBadgeView == null) {
					mQBadgeView = new QBadgeView(mContext);
					badge = mQBadgeView.bindTarget(ivImage).setGravityOffset(0, 0, false);
					objs[0] = mQBadgeView;
					objs[1] = badge;
				}
				if (badge == null) {
					badge = mQBadgeView.bindTarget(ivImage).setGravityOffset(0, 0, false);
					objs[1] = badge;
				}
				badge.setBadgeNumber(count);
				ViewGroup.LayoutParams lp = (ViewGroup.LayoutParams) ivImage.getLayoutParams();
				int width = (int) (imageWidth + (mQBadgeView.getBadgeViewWidth() - ViewUtil.dp2px(mContext, 6)) * 2);
				int maxWidth = ViewUtil.getScreenSize((Activity) mContext).widthPixels / tabIds.length;
				if (width > maxWidth) {
					width = maxWidth;
				}
				lp.width = width;
				ivImage.setLayoutParams(lp);
				isLoadingMessage = false;
			}
			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub

			}
		};
		mMessageTask.execute();
	}

	public void switchMainScreen(Class<?> cls, String url){
		Intent intent = new Intent(this, cls);
		intent.putExtra("url", url);
		intent.putExtra(SPConstants.IS_FIT_STATUS_BAR, false);
		Window window = getLocalActivityManager().startActivity(cls.getName(), intent);
		View view = window.getDecorView();
		ViewGroup viewGroup = (ViewGroup) findViewById(R.id.view_content);
		viewGroup.removeAllViews();
		viewGroup.addView(view);
	}

	public void onTabSelected(int tab) {
		// TODO Auto-generated method stub
		switch (tab) {
			case TAB_HOME:
				switchMainScreen(ChatActivity.class, "");
				break;
			case TAB_APP_LIST:
				switchMainScreen(AppListActivity.class, "");
				break;
			case TAB_USER:
				switchMainScreen(SettingActivity.class, "");
				break;
			default:
				break;
		}
	}

	private Handler mConnectHandler = new Handler(Looper.getMainLooper()) {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case MessageConstants.CONNECTED:
					mTvTitle.setText(getString(R.string.ebei_app_name));
					mTitleProgressBar.setVisibility(View.GONE);
					break;
				case MessageConstants.CONNECTING:
					mTvTitle.setText(getString(R.string.ebei_do_reconnect));
					mTitleProgressBar.setVisibility(View.VISIBLE);
					break;
				case MessageConstants.DISCONNECTED:
					mTvTitle.setText(getString(R.string.ebei_no_connect));
					mTitleProgressBar.setVisibility(View.GONE);
					break;
				default:
					break;
			}
		}
	};

	private static boolean isExiting = false;
	private Timer mExitTimer;
	private TimerTask mExitTask;

	@Override
	public void onBackPressed() {
		if (isExiting == false) {
			if ((mExitTimer != null)) {
				mExitTimer.cancel();
				mExitTimer = null;
				mExitTask = null;
			}
			mExitTimer = new Timer();
			mExitTask = new TimerTask() {
				@Override
				public void run() {
					isExiting = false;
				}
			};
			isExiting = true;
			ViewUtil.toastMsg(mContext, R.string.ebei_exit_confirm);
			mExitTimer.schedule(mExitTask, 2000);
		} else {
			finish();
		}
	}

}
